import { defineStore } from 'pinia'
import { userService } from '../services/api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    currentUser: (state) => state.user
  },
  
  actions: {
    async login(credentials) {
      try {
        const { token, user } = await userService.login(credentials)
        this.token = token
        this.user = user
        localStorage.setItem('token', token)
        return true
      } catch (error) {
        console.error('Login failed:', error)
        throw error
      }
    },
    
    async register(userData) {
      try {
        const { token, user } = await userService.register(userData)
        this.token = token
        this.user = user
        localStorage.setItem('token', token)
        return true
      } catch (error) {
        console.error('Registration failed:', error)
        throw error
      }
    },
    
    async fetchCurrentUser() {
      try {
        const user = await userService.getCurrentUser()
        this.user = user
        return user
      } catch (error) {
        console.error('Failed to fetch current user:', error)
        throw error
      }
    },
    
    async updateProfile(data) {
      try {
        const user = await userService.updateProfile(data)
        this.user = user
        return user
      } catch (error) {
        console.error('Failed to update profile:', error)
        throw error
      }
    },
    
    logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
    }
  }
}) 